<template>
    <div class="main1 elResetBody" v-if="userAuth[viewAuthCode] && forSourceViewId">
        <view-detail-in :id="forSourceViewId" @showDetail="showDetail"
            style="margin-top: 10px; height: calc(100% - 10px);"></view-detail-in>
        <viewDetailPage v-if="childDigVisible" :id="childId" :param="childParam" @closeDig="childDigVisible = false" />
    </div>
</template>

<script setup lang="ts">
import { hasAuth } from '@/utils/checkAuthCode';
import useUserStore from '@/store/modules/user';
// import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import viewDetailPage from '@/layout/data/resource/resourceView/detailPage.vue';
import viewDetailIn from '@/layout/data/resource/resourceView/detailIn.vue';

const userAuth = ref<Record<string, boolean>>({});
const userStore = useUserStore();
const viewAuthCode = ref('');
const route = useRoute();
const forSourceViewId = ref<number | null>(0);

// 使用 ref 管理停止函数
const stopRouteWatch = ref<(() => void) | undefined>(undefined);

onMounted(() => {
    updatePageData();

    // 创建监听并保存停止函数
    stopRouteWatch.value = watch(
        () => route.name,
        () => {
            console.log('路由变化，更新页面数据');
            updatePageData();
        }
    );
});

// 在组件卸载时取消监听
onUnmounted(() => {
    if (stopRouteWatch.value) {
        stopRouteWatch.value(); // 执行停止监听函数
        console.log('已移除路由监听'); // 确保打印日志
    } else {
        console.warn('未找到路由监听器，无法移除'); // 添加警告以排查问题
    }
});

const updatePageData = () => {
    const routeName = route.name as string | undefined;
    if (routeName) {
        // 获取查看权限点code
        viewAuthCode.value = `${routeName}_view`;
        // 获取权限点集合
        userAuth.value = hasAuth([viewAuthCode.value]);
        // 获取所有菜单信息
        const menu = userStore.userInfo.userMenu;

        // 新增：查找与routeName相同的code对象所对应的forSourceViewId
        const findForSourceViewId = (menus: any[], routeName: string): number | null => {
            for (const menu of menus) {
                if (menu.children) {
                    const result = findForSourceViewId(menu.children, routeName);
                    if (result !== null) return result;
                }
                if (menu.code == routeName && menu.forSourceViewId) {
                    return menu.forSourceViewId;
                }
            }
            return null;
        };
        // 获得当前资源报表页对应的资源id
        forSourceViewId.value = findForSourceViewId(menu, routeName);
        // console.log('当前资源报表页对应的资源id:', forSourceViewId);
    }
};

// 递归组件的状态
const childDigVisible = ref(false);
const childId = ref(0);
const childParam = ref<Record<string, any>>({});
const showDetail = (objs: any) => {
    let msg = { ...objs };
    // 设置递归组件的参数
    childId.value = msg.childId;
    childParam.value = msg.childParam;
    childDigVisible.value = true; // 打开递归组件
};
</script>
